package com.yunbiao.ybbusstopplate.ui.fragment

import android.content.res.Configuration
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.LinearLayout
import com.blankj.utilcode.util.UiMessageUtils
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.yunbiao.ybbusstopplate.R
import com.yunbiao.ybbusstopplate.base.BaseFragment
import com.yunbiao.ybbusstopplate.bean.SiteInfoBean
import com.yunbiao.ybbusstopplate.serialport.SerTool
import com.yunbiao.ybbusstopplate.serialport.SerialPortConfig
import com.yunbiao.ybbusstopplate.ui.view.SubwayLooper
import com.yunbiao.ybbusstopplate.ui.view.SubwayLooper2
import com.yunbiao.ybbusstopplate.ui.view.subway.StationEffect
import com.yunbiao.ybbusstopplate.ui.view.subway.StationMap
import com.yunbiao.ybbusstopplate.ui.view.subway.StationMap2
import com.yunbiao.ybbusstopplate.ui.view.subway.StationMap3
import com.yunbiao.ybbusstopplate.utils.SpTool
import com.yunbiao.ybbusstopplate.utils.eventbus.EventMessage
import com.yunbiao.ybbusstopplate.utils.eventbus.EventTAG
import kotlinx.android.synthetic.main.fragment_leshan_site.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class LeshanSiteFragment :BaseFragment() {
    companion object{
        fun getInstance():LeshanSiteFragment{
            val busStopPlateFragment = LeshanSiteFragment()

            return busStopPlateFragment
        }
    }

    private  var  isPORTRAIT=false;//是否是竖屏


    override fun getViewId(): Int {
        return R.layout.fragment_leshan_site
    }

    override fun initData() {
        EventBus.getDefault().register(this)

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            isPORTRAIT=true
        }else{
            isPORTRAIT=false
        }

        //开启串口
        SerTool.startPort()

//        val animationDrawable = img_goto.background as AnimationDrawable
//        if (animationDrawable!=null){
//            animationDrawable?.start()
//        }

        initDataOnStart()
    }

    override fun initListener() {
        val configShowLineType = SpTool.getConfigShowLineType()
        Log.e("2222","configShowLineType----------------->$configShowLineType")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(eventMessage: EventMessage){
        when(eventMessage.msgTag){
            //切换上下行
            EventTAG.EVENT_UPDATESITELIST->{
                val lineList = eventMessage.msgData as ArrayList<String>
                updateLineList(lineList)
            }
            //线路信息
            EventTAG.EVENT_LINEINFO->{
                val lineInfo = eventMessage.msgData as Array<String>
                this.lineInfo=lineInfo
                updateLine(lineInfo)
            }
            //首末班时间更新
            EventTAG.EVENT_SITETIME->{
                val timeInfo = eventMessage.msgData as Array<String>
                val s1 = timeInfo[0]
                val e1 = timeInfo[1]
                val s2 = timeInfo[2]
                val e2 = timeInfo[3]

                SpTool.saveSiteTime(s1, e1, s2, e2)

                updateSiteTime2()
//                if (ll_tip.visibility==View.VISIBLE){
//                    ll_tip.visibility =View.INVISIBLE
//                }
//                if (TextUtils.isEmpty(s1)){
//                    SpTool.cleanSiteStartTime()
//                }else{
//                    if (lineInfo!=null&&lineInfo!!.size>=3){
//                        val s = lineInfo!![1]
//                        if (!TextUtils.isEmpty(s)){
//                            SpTool.saveSiteStartTime(s,s1,e1)
//                        }
//                    }
//                }
//
//                if (TextUtils.isEmpty(s2)){
//                    SpTool.cleanSiteEndTime()
//                }else{
//                    if (lineInfo!=null&&lineInfo!!.size>=3){
//                        val s = lineInfo!![2]
//                        if (!TextUtils.isEmpty(s)){
//                            SpTool.saveSiteEndTime(s,s2,e2)
//                        }
//                    }
//                }
//                SpTool.saveSiteTime(s1,e1,s2,e2)
//                updateSiteTime()
            }
            //到站、离站提示
            EventTAG.EVENT_SITETIP->{
                val siteInfo = eventMessage.msgData as SiteInfoBean
                if (siteInfo==null){
                    return
                }
                showTip(siteInfo)
            }
            //更新配置
            EventTAG.event_config_update->{
                //重新打开串口
               SerTool.startPort()
            }
        }
    }

    //初始化数据
    private var globalListener:ViewTreeObserver.OnGlobalLayoutListener?=null
    private fun initDataOnStart(){
        var lineName = SpTool.get_line_name()
        if (!TextUtils.isEmpty(lineName)){
            //去除自己添加的“路”
            if(lineName.contains("路")){
                lineName = lineName.replace("路","");
            }
//            val lastIndexOf = lineName.lastIndexOf("路")
//            if (lastIndexOf>0){
//                lineName=lineName.substring(0,lastIndexOf)
//            }
//            //去除串口返回自带的“路”
//            val lastIndexOf2 = lineName.lastIndexOf("路")
//            if (lastIndexOf2>0){
//                lineName=lineName.substring(0,lastIndexOf2)
//            }
//            tv_linenum.text=lineName
            UiMessageUtils.getInstance().send(LeshanLineInfoFragment.EVENT_LINE_NAME,lineName)
        }

        val siteStart = SpTool.get_site_start()
        if (!TextUtils.isEmpty(siteStart)){
//            tv_site_start.text=siteStart
//            tv_site_start1.text=siteStart
            UiMessageUtils.getInstance().send(LeshanLineInfoFragment.EVENT_LINE_START,siteStart)
        }

        val siteEnd = SpTool.get_site_end()
        if (!TextUtils.isEmpty(siteEnd)){
//            tv_site_end.text=siteEnd
//            tv_site_end1.text=siteEnd
            UiMessageUtils.getInstance().send(LeshanLineInfoFragment.EVENT_LINE_END,siteEnd)
        }

        //todo 更新起始站、终点站时间
//        updateSiteTime()
        updateSiteTime2()

        val siteList = SpTool.get_site_list()
        if (!TextUtils.isEmpty(siteList)){
            val sites = siteList.split(",")
            if (sites==null||sites.size<=0){
                return
            }
//            tv_sitename.setText(sites[0])
            val tempList = arrayListOf<String>()
            for (s in sites){
                tempList.add(s)
            }

//            for (s in 1..50){
//                tempList.add("这是一个简单（文字"+s+")")
//            }

            list=tempList
            globalListener=object :ViewTreeObserver.OnGlobalLayoutListener{
                override fun onGlobalLayout() {
                    updateLineListUI(tempList)
                    updateSplashDot()
                    fl_linelist.viewTreeObserver.removeOnGlobalLayoutListener(globalListener)
                }
            }
            fl_linelist.viewTreeObserver.addOnGlobalLayoutListener(globalListener)
        }
    }
    /**
     * 公交站点ui
     */
    private var stationMap:StationMap?=null//全屏
//    private var loopView:BusStopLoopView?=null//轮播
    private var loopView:SubwayLooper?=null//轮播
    private fun updateLineListUI(lineList: ArrayList<String>){
        if (stationMap!=null){
            fl_linelist.removeView(stationMap)
            stationMap=null
        }
//        if (loopView!=null){
//            fl_linelist.removeView(loopView!!)
//            loopView=null
//        }
        if (loopView!=null){
            loopView!!.desty()
            fl_linelist.removeAllViews()
            loopView=null
        }
        val lineType = SpTool.getConfigShowLineType()
        if (lineType==1){//全屏
            val ss = arrayOfNulls<String>(lineList!!.size)
            val array = lineList!!.toArray(ss)
            val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            var limitStationNum=23
            val configShowAdvert = SpTool.getConfigShowAdvert()
            if (!configShowAdvert){
                limitStationNum=47
            }

            if (isPORTRAIT){
                StationMap3.STATIONMAP_MAXFONTSIZE = fl_linelist.tag.toString().toInt()
                loopView = SubwayLooper2(context,fl_linelist,lineList!!.size)
                loopView!!.setDatas(lineList)
            }else{
                StationMap.STATIONMAP_MAXFONTSIZE = fl_linelist.tag.toString().toInt()
                stationMap = StationMap(context, array,limitStationNum)
                stationMap!!.setWidth_Height(fl_linelist.width,fl_linelist.height)
                stationMap!!.SetStationNum(array!!.size)
                fl_linelist!!.addView(stationMap!!, params)
            }


        }else{
            fl_linelist.removeAllViews()
            val showAdvert = SpTool.getConfigShowAdvert()
            var count=50
            if (showAdvert){
                count=30
            }

            if (isPORTRAIT){
                StationMap3.STATIONMAP_MAXFONTSIZE = fl_linelist.tag.toString().toInt()
                loopView = SubwayLooper2(context,fl_linelist,count)
            }else{
                StationMap2.STATIONMAP_MAXFONTSIZE = fl_linelist.tag.toString().toInt()
                loopView = SubwayLooper(context,fl_linelist,count)
            }


            loopView!!.setDatas(lineList)

//            loopView = BusStopLoopView(context)
//            var layoutParams= FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
//            layoutParams.setMargins(15,0,15,0)
//            loopView!!.getViewTreeObserver().addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
//                override fun onGlobalLayout() {
//                    loopView!!.setSites(lineList,loopView!!.width)
//                    loopView!!.getViewTreeObserver().removeOnGlobalLayoutListener(this)
//                }
//            })
//            fl_linelist.addView(loopView,layoutParams)
        }

    }

    /**
     * 下一站闪烁点
     */
    private var effect:StationEffect?=null
    private fun updateSplashDot(){
        if (effect != null) {
            effect!!.threadstop()
            fl_linelist.removeView(effect)
            effect = null
        }
        val lineType = SpTool.getConfigShowLineType()
        if (lineType==1){//全屏
            effect = StationEffect(context)
            fl_linelist.addView(effect)
        }
    }

    /**
     * 更新右侧数据
     */
    private var list:ArrayList<String>?=null
    private fun updateLineList(lineList: ArrayList<String>){
        if (lineList==null||lineList.size<=0){
            return
        }
//        tv_sitename.setText(lineList[0])
        list=lineList
        updateLineListUI(lineList)
        saveLines(lineList)
        updateSplashDot()
    }

    /**
     * 更新首末班时间
     */

    private fun updateSiteTime2(){
//        ll_site_start.visibility=View.GONE
//        ll_site_end.visibility=View.GONE

//        return

        val showLineTime = SpTool.getConfigShowLineTime()
        if (!showLineTime){
            return
        }else{
            val siteTime = SpTool.getSiteTime()
            if (siteTime==null||siteTime.size<=0){
                return
            }
            //起始站
            val s1 = siteTime[0]
            if (!TextUtils.isEmpty(s1)){
                var ss="首班"+s1+"  末班"+siteTime[1]
//                tv_site_start_time.text=ss
//                ll_site_start.visibility=View.VISIBLE
            }
            //终点站
            val s2 = siteTime[2]
            if (!TextUtils.isEmpty(s1)){
                var ss="首班"+s2+"  末班"+siteTime[3]
//                tv_site_end_time.text=ss
//                ll_site_end.visibility=View.VISIBLE
            }
        }
    }

    /*private fun updateSiteTime(){
        ll_site_start.visibility=View.GONE
        ll_site_end.visibility=View.GONE

        val showLineTime = SpTool.getConfigShowLineTime()
        if (!showLineTime){
            return
        }else{
            val siteStartTime = SpTool.getSiteStartTime()
            val siteEndTime = SpTool.getSiteEndTime()
            if (TextUtils.isEmpty(siteStartTime)){
                return
            }
            val startSplit = siteStartTime.split(";")
            val startName = startSplit[0]
            var endSplit:List<String>?=null
            var endName=""
            if (!TextUtils.isEmpty(siteEndTime)){
                endSplit = siteEndTime.split(";")
                endName = endSplit[0]
            }
            //起始站首末班时间
            val sStartText = tv_site_start1.text.toString().trim()
            if (TextUtils.isEmpty(sStartText)||"起始站".equals(sStartText)){
                return
            }
            if (sStartText.equals(startName)){
                val siteTime = startSplit[1].split(",")
                tv_site_start_time.text="首班"+siteTime[0]+"  末班"+siteTime[1]
                ll_site_start.visibility=View.VISIBLE
            }else if (sStartText.equals(endName)){
                val siteTime = endSplit!![1].split(",")
                tv_site_start_time.text="首班"+siteTime[0]+"  末班"+siteTime[1]
                ll_site_start.visibility=View.VISIBLE
            }else{
                tv_site_start_time.text=""
            }

            //终点站首末班时间
            val sEndText = tv_site_end1.text.toString().trim()
            if (TextUtils.isEmpty(sEndText)||"终点站".equals(sEndText)){
                return
            }
            if (sEndText.equals(startName)){
                val siteTime = startSplit[1].split(",")
                tv_site_end_time.text="首班"+siteTime[0]+"  末班"+siteTime[1]
                ll_site_end.visibility=View.VISIBLE
            }else if (sEndText.equals(endName)){
                val siteTime = endSplit!![1].split(",")
                tv_site_end_time.text="首班"+siteTime[0]+"  末班"+siteTime[1]
                ll_site_end.visibility=View.VISIBLE
            }else{
                tv_site_end_time.text=""
            }
        }
    }*/

    private fun saveLines(lineList: ArrayList<String>){
        val builder = StringBuilder()
        for (ss in lineList){
            builder.append(ss+",")
        }
        var lines = builder.toString()
        lines=lines.substring(0,lines.lastIndexOf(","))
        SpTool.save_site_list(lines)
    }

    /**
     * 更新线路
     */
    private var lineInfo: Array<String>?=null
    private fun updateLine(lineInfo: Array<String>){
        //触发更新线路，默认首次到达
        arriveFirst=true

        var lineName = lineInfo[0]
        if (lineName.contains("路")) {
            lineName = lineName.replace("路","")
        }

//        tv_linenum.text=lineName
//        tv_site_start.text=lineInfo[1]
//        tv_site_end.text=lineInfo[2]
//        tv_site_start1.text=lineInfo[1]
//        tv_site_end1.text=lineInfo[2]

        UiMessageUtils.getInstance().send(LeshanLineInfoFragment.EVENT_LINE_NAME,lineName)
        UiMessageUtils.getInstance().send(LeshanLineInfoFragment.EVENT_LINE_START,lineInfo[1])
        UiMessageUtils.getInstance().send(LeshanLineInfoFragment.EVENT_LINE_END,lineInfo[2])

        //通卡设备特殊处理
        if(SerialPortConfig.PORT_TYPE==SerialPortConfig.TYPE_TK){
            val lineName = SpTool.get_line_name()
            val siteTime = SpTool.getSiteTime()
            //线路没变化并且有之前时间
            if ((lineInfo[0]+"路").equals(lineName)&&siteTime!=null){
                val startSiteLocal = SpTool.get_site_start()
                val startName = lineInfo[1]
                //起始站更换,交换时间顺序
                if (!startName.equals(startSiteLocal)){
                    val s1 = siteTime[0]
                    val e1 = siteTime[1]
                    val s2 = siteTime[2]
                    val e2 = siteTime[3]

                    SpTool.saveSiteTime(s2,e2,s1,e1)
                }
                //刷新
                updateSiteTime2()
            }else{
                //清除时间
                SpTool.cleanSiteTime()
                updateSiteTime2()
            }
        }else{
            //清除时间
            SpTool.cleanSiteTime()
            updateSiteTime2()
        }
//        updateSiteTime()
        saveLineInfo(lineInfo)
    }

    private fun saveLineInfo(lineInfo: Array<String>){
        SpTool.save_line_name(lineInfo[0]+"路")
        SpTool.save_site_start(lineInfo[1])
        SpTool.save_site_end(lineInfo[2])
    }

    fun getPositon(name:String):Int{
        var indexOf = list!!.indexOf(name)
        if(indexOf == -1){
            indexOf = 0;
        }
        return indexOf
    }
    /**
     * 信息提示
     */
    private var playoff:YoYo.YoYoString?=null
    private var playon:YoYo.YoYoString?=null
    private var arriveFirst=false
    private fun showTip(siteInfo: SiteInfoBean){
        var index = siteInfo.index
        var siteName=""
        if (index < 0){
            siteName = siteInfo.siteName
        }else{
            if (index>=list!!.size){
                index=list!!.size-1
            }
            siteName=list!!.get(index)
        }
        if (TextUtils.isEmpty(siteName)){
            return
        }
        //显示当前站名
        tv_tip_site.text=siteName
        if (siteInfo.stutas==1){//到站
            val lineType = SpTool.getConfigShowLineType()
            var positon = 0
            if (SerialPortConfig.PORT_TYPE == SerialPortConfig.TYPE_HX) {
                positon = siteInfo.index;
            } else {
                positon = getPositon(siteName)
            }

//            val positon = getPositon(siteName)
            if (positon==0||arriveFirst){//首站
                arriveFirst=false

                if (isPORTRAIT){
                    loopView!!.setCurrenPosition(0)
                }else{
                    if (lineType==1){
                        stationMap!!.SetStationCur(0)
                    }else{
                        loopView!!.setCurrenPosition(0)
                    }
                }
//                return
            }
//            tv_sitename.text=siteInfo.siteName
            tv_tip_arrived.visibility=View.VISIBLE
            tv_tip_next.visibility=View.GONE
            tv_tip2.text="开门请当心，下车时注意安全！"

            Log.e("111","ll_tip.visibility-------->${ll_tip.visibility}")
            //没有显示，动画报站
            if (ll_tip.visibility!=View.VISIBLE){
                showon()
            }
            if (isPORTRAIT){
                loopView!!.setCurrenPosition(positon)
            }else{
                if (lineType==1){
                    stationMap!!.SetStationCur(positon)
                }else{
                    loopView!!.setCurrenPosition(positon)
                }
            }


            //末站,10s后自动隐藏
            if (siteInfo.siteName.equals(list!!.get(list!!.size-1))){
                showoff(10)
            }

        }else{//下一站
            tv_tip_arrived.visibility=View.GONE
            tv_tip_next.visibility=View.VISIBLE
            tv_tip2.text="车辆起步，请坐稳扶好！"
            var showTime = siteInfo.showTime
            if (showTime<10){
                showTime=10
            }
            showoff(showTime)
        }
    }

    private fun stopOff(){
        if(playoff != null){
            playoff!!.stop()
        }
    }

    private fun showon(){
        stopOff()
        playon=YoYo.with(Techniques.SlideInRight)
            .duration(1000)
            .onStart {
                ll_tip.visibility=View.VISIBLE
            }
            .onEnd({
                ll_tip.visibility=View.VISIBLE
            })
            .playOn(ll_tip)
    }

    private fun showoff(showTime:Int){
        stopOff()
        playoff = YoYo.with(Techniques.SlideOutRight)
            .duration(1000)
            .delay(showTime * 1000L)
            .onStart {
                ll_tip.visibility = View.VISIBLE
            }
            .onEnd({
                ll_tip.visibility = View.INVISIBLE
            })
            .playOn(ll_tip)
    }
    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        //关闭
        SerTool.closePort()
        if (playon!=null&&playon!!.isRunning){
            playon!!.stop()
        }
        if (playoff!=null&&playoff!!.isRunning){
            playoff!!.stop()
        }
        if (effect != null) {
            effect!!.threadstop()
            if (fl_linelist!=null){
                fl_linelist.removeView(effect)
            }
            effect = null
        }
        super.onDestroy()
    }

}